package com.xaicode.learn.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:29
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // read client msg
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("ctx: {}", ctx);

        // read client student
        if (msg instanceof StudentPOJO.Student) {
            StudentPOJO.Student student = (StudentPOJO.Student) msg;
            log.info("receive client Student id={}, name={}", student.getId(), student.getName());
        }

    }

    // read client msg complete
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        log.info("read client msg complete");

        // write and flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("server complete: hello client", CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
